<template>
  <div class="jsa-confirm">
    <div class="page-container">
      <div class="page-header">
        <h2>JSA确认</h2>
        <div class="header-actions">
          <el-button @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <el-button type="success" @click="submitConfirm" :loading="submitting">
            <el-icon><Check /></el-icon>
            确认JSA
          </el-button>
        </div>
      </div>
      
      <div v-if="jsaData" class="jsa-content">
        <!-- 基本信息 -->
        <el-card class="info-card">
          <template #header>
            <span>基本信息</span>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <label>JSA编号：</label>
                <span class="jsa-number">{{ jsaData.jsaNumber }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>关联许可证：</label>
                <span>{{ jsaData.permitNumber }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>作业类型：</label>
                <el-tag :type="getWorkTypeTagType(jsaData.workType)">
                  {{ getWorkTypeLabel(jsaData.workType) }}
                </el-tag>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <label>作业地点：</label>
                <span>{{ jsaData.location }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>创建人：</label>
                <span>{{ jsaData.creator }}</span>
              </div>
            </el-col>
          </el-row>
          
          <div class="info-item">
            <label>作业描述：</label>
            <p>{{ jsaData.workDescription }}</p>
          </div>
        </el-card>
        
        <!-- JSA分析表 -->
        <el-card class="info-card">
          <template #header>
            <span>JSA分析表</span>
          </template>
          <el-table :data="jsaData.analysisSteps" border>
            <el-table-column label="序号" width="80" align="center">
              <template #default="{ $index }">
                {{ $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="step" label="作业步骤" width="200" />
            <el-table-column prop="risk" label="潜在风险" width="200" />
            <el-table-column prop="controlMeasure" label="管控措施" />
            <el-table-column prop="responsiblePerson" label="责任人" width="120">
              <template #default="{ row }">
                {{ getPersonName(row.responsiblePerson) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        
        <!-- 分析人员 -->
        <el-card class="info-card">
          <template #header>
            <span>分析人员</span>
          </template>
          <div class="analyzer-list">
            <el-tag
              v-for="analyzer in jsaData.analyzers"
              :key="analyzer.id"
              style="margin-right: 8px; margin-bottom: 8px"
            >
              {{ analyzer.name }} ({{ analyzer.department }})
            </el-tag>
          </div>
        </el-card>
        
        <!-- 确认要求 -->
        <el-card class="confirm-card">
          <template #header>
            <span>确认要求</span>
          </template>
          
          <div class="confirm-requirements">
            <h4>需要确认的人员类型：</h4>
            <div class="requirement-list">
              <el-tag
                v-for="requirement in jsaData.confirmers"
                :key="requirement"
                type="info"
                style="margin-right: 8px; margin-bottom: 8px"
              >
                {{ getConfirmerLabel(requirement) }}
              </el-tag>
            </div>
          </div>
          
          <div class="confirm-deadline">
            <h4>确认截止时间：</h4>
            <p class="deadline-text">{{ jsaData.confirmDeadline }}</p>
          </div>
        </el-card>
        
        <!-- 确认表单 -->
        <el-card class="confirm-form-card">
          <template #header>
            <span>确认表单</span>
          </template>
          
          <el-form
            :model="confirmForm"
            :rules="confirmRules"
            ref="confirmFormRef"
            label-width="120px"
          >
            <el-form-item label="确认类型" prop="confirmType">
              <el-radio-group v-model="confirmForm.confirmType">
                <el-radio value="analyzer">分析人员确认</el-radio>
                <el-radio value="responsible">措施责任人确认</el-radio>
                <el-radio value="safety_officer">安全员确认</el-radio>
                <el-radio value="supervisor">主管确认</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="确认意见" prop="confirmOpinion">
              <el-radio-group v-model="confirmForm.confirmOpinion">
                <el-radio value="agree">同意</el-radio>
                <el-radio value="disagree">不同意</el-radio>
                <el-radio value="suggest">有建议</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="确认说明" prop="confirmComment">
              <el-input
                v-model="confirmForm.confirmComment"
                type="textarea"
                :rows="4"
                placeholder="请输入确认说明或建议"
              />
            </el-form-item>
            
            <el-form-item v-if="confirmForm.confirmOpinion === 'suggest'" label="具体建议" prop="suggestions">
              <el-input
                v-model="confirmForm.suggestions"
                type="textarea"
                :rows="3"
                placeholder="请输入具体的修改建议"
              />
            </el-form-item>
            
            <el-form-item label="风险认知" prop="riskAwareness">
              <el-checkbox-group v-model="confirmForm.riskAwareness">
                <el-checkbox value="understand_risks">我已充分了解作业风险</el-checkbox>
                <el-checkbox value="understand_measures">我已了解相关管控措施</el-checkbox>
                <el-checkbox value="agree_measures">我同意并支持相关管控措施</el-checkbox>
                <el-checkbox value="will_follow">我将严格按照JSA要求执行</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'

const router = useRouter()

interface AnalysisStep {
  step: string
  risk: string
  controlMeasure: string
  responsiblePerson: string
}

interface Analyzer {
  id: string
  name: string
  department: string
}

interface JSAData {
  id: number
  jsaNumber: string
  permitNumber: string
  workType: string
  location: string
  creator: string
  workDescription: string
  analysisSteps: AnalysisStep[]
  analyzers: Analyzer[]
  confirmers: string[]
  confirmDeadline: string
}

interface ConfirmForm {
  confirmType: string
  confirmOpinion: string
  confirmComment: string
  suggestions: string
  riskAwareness: string[]
}

const jsaData = ref<JSAData | null>(null)
const confirmFormRef = ref<FormInstance>()
const submitting = ref(false)

const confirmForm = reactive<ConfirmForm>({
  confirmType: '',
  confirmOpinion: '',
  confirmComment: '',
  suggestions: '',
  riskAwareness: []
})

const confirmRules: FormRules = {
  confirmType: [
    { required: true, message: '请选择确认类型', trigger: 'change' }
  ],
  confirmOpinion: [
    { required: true, message: '请选择确认意见', trigger: 'change' }
  ],
  confirmComment: [
    { required: true, message: '请输入确认说明', trigger: 'blur' }
  ],
  riskAwareness: [
    { required: true, message: '请确认风险认知', trigger: 'change' }
  ]
}

// 人员数据
const personnelData = [
  { id: '1', name: '张三', department: '维修部' },
  { id: '2', name: '李四', department: '维修部' },
  { id: '3', name: '王五', department: '安全部' },
  { id: '4', name: '赵六', department: '生产部' }
]

// 获取JSA数据
const fetchJSAData = async () => {
  try {
    // 从路由参数获取JSA ID
    const route = useRoute()
    const jsaId = route.params.id
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 根据ID获取对应的JSA数据
    const mockJSAData = {
      '1': {
        id: 1,
        jsaNumber: 'JSA20250115001',
        permitNumber: 'WP20250115001',
        workType: 'high_altitude',
        location: 'A区3楼外墙维修',
        creator: '张三',
        workDescription: '外墙保温层维修，需要高空作业',
        analysisSteps: [
          {
            step: '作业前准备',
            risk: '人员坠落',
            controlMeasure: '检查安全带、安全帽等防护用品',
            responsiblePerson: '1'
          },
          {
            step: '搭建脚手架',
            risk: '脚手架倒塌',
            controlMeasure: '按规范搭建，设置防护网',
            responsiblePerson: '2'
          },
          {
            step: '高空作业',
            risk: '工具坠落',
            controlMeasure: '使用工具袋，设置警戒区',
            responsiblePerson: '1'
          }
        ],
        analyzers: [
          { id: '1', name: '张三', department: '维修部' },
          { id: '3', name: '王五', department: '安全部' }
        ],
        confirmers: ['analyzers', 'responsible_persons', 'safety_officer'],
        confirmDeadline: '2025-01-16 18:00'
      },
      '2': {
        id: 2,
        jsaNumber: 'JSA20250115002',
        permitNumber: 'WP20250115002',
        workType: 'hot_work',
        location: 'B区管道焊接',
        creator: '李四',
        workDescription: '管道焊接作业，需要动火作业',
        analysisSteps: [
          {
            step: '作业前准备',
            risk: '火灾爆炸',
            controlMeasure: '检查动火区域，准备灭火器材',
            responsiblePerson: '2'
          },
          {
            step: '焊接作业',
            risk: '火花飞溅',
            controlMeasure: '设置防火毯，清理周围可燃物',
            responsiblePerson: '2'
          }
        ],
        analyzers: [
          { id: '2', name: '李四', department: '维修部' },
          { id: '3', name: '王五', department: '安全部' }
        ],
        confirmers: ['analyzers', 'responsible_persons', 'safety_officer'],
        confirmDeadline: '2025-01-17 18:00'
      }
    }
    
    jsaData.value = mockJSAData[jsaId as string] || mockJSAData['1']
  } catch (error: any) {
    ElMessage.error(error.message || '获取JSA数据失败')
  }
}

// 获取人员姓名
const getPersonName = (personId: string) => {
  const person = personnelData.find(p => p.id === personId)
  return person ? person.name : '未知'
}

// 获取作业类型标签类型
const getWorkTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    high_altitude: 'warning',
    hot_work: 'danger',
    electrical: 'primary',
    confined_space: 'info',
    lifting: 'success'
  }
  return typeMap[type] || 'info'
}

// 获取作业类型标签
const getWorkTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    high_altitude: '高空作业',
    hot_work: '动火作业',
    electrical: '电气作业',
    confined_space: '受限空间',
    lifting: '起重作业'
  }
  return labelMap[type] || type
}

// 获取确认人员标签
const getConfirmerLabel = (requirement: string) => {
  const labelMap: Record<string, string> = {
    analyzers: '分析人员',
    responsible_persons: '措施责任人',
    safety_officer: '安全员',
    supervisor: '主管'
  }
  return labelMap[requirement] || requirement
}

// 提交确认
const submitConfirm = async () => {
  if (!confirmFormRef.value) return
  
  try {
    await confirmFormRef.value.validate()
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    ElMessage.success('JSA确认提交成功')
    router.push('/jsa/list')
  } catch (error: any) {
    ElMessage.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 返回
const goBack = () => {
  router.push('/jsa/list')
}

onMounted(() => {
  fetchJSAData()
})
</script>

<style lang="scss" scoped>
.jsa-confirm {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .jsa-content {
    .info-card {
      margin-bottom: 20px;
      
      .info-item {
        margin-bottom: 12px;
        
        label {
          font-weight: 500;
          color: #333;
          margin-right: 8px;
        }
        
        .jsa-number {
          font-weight: bold;
          color: #409eff;
          font-size: 16px;
        }
        
        p {
          margin: 8px 0 0 0;
          color: #666;
          line-height: 1.5;
        }
      }
    }
    
    .analyzer-list {
      min-height: 40px;
    }
    
    .confirm-card {
      margin-bottom: 20px;
      
      .confirm-requirements {
        margin-bottom: 20px;
        
        h4 {
          color: #333;
          margin-bottom: 12px;
        }
      }
      
      .confirm-deadline {
        h4 {
          color: #333;
          margin-bottom: 8px;
        }
        
        .deadline-text {
          color: #e6a23c;
          font-weight: bold;
          font-size: 16px;
        }
      }
    }
    
    .confirm-form-card {
      .el-form-item {
        margin-bottom: 20px;
      }
    }
  }
}
</style>

